package com.example.springtest.people.service.impl;


import com.example.springtest.common.ServiceCode;
import com.example.springtest.common.ServiceException;
import com.example.springtest.people.mapper.PeopleMapper;
import com.example.springtest.people.pojo.dto.PeopleDTO;
import com.example.springtest.people.pojo.entity.People;
import com.example.springtest.people.pojo.vo.AvatarVO;
import com.example.springtest.people.pojo.vo.PeopleVO;
import com.example.springtest.people.service.PeopleService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 业务层
 */
@Service
@Transactional
@Slf4j

public class PeopleServiceImpl implements PeopleService {
    @Autowired
    private PeopleMapper peopleMapper;
      @Override
      /**
       * 查询所有学生
       */
    public List<PeopleVO> getPeopleList(){
          List<People> peopleList= peopleMapper.getList();
          if(peopleList.isEmpty()){
              throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在学生");
          }
        List<PeopleVO> peopleVOList=new ArrayList<>();
        peopleList.forEach(people ->{
            PeopleVO peopleVO=new PeopleVO();
            peopleVO.setId(people.getId());
            peopleVO.setName(people.getName());
            peopleVO.setSex(people.getSex());
            peopleVO.setAge(people.getAge());
            peopleVO.setMajor(people.getMajor());
            peopleVO.setCode(people.getCode());
            peopleVO.setAddress(people.getAddress());
            peopleVO.setStatus(people.getStatus());
            peopleVOList.add(peopleVO);
        });
        return peopleVOList;
    }

    /**
     * 增加学生
     * @param peopleDTO
     */
    @Override
    public void addPeople(PeopleDTO peopleDTO){
        People people=new People();
        people.setName(peopleDTO.getName());
        people.setSex(peopleDTO.getSex());
        people.setMajor(peopleDTO.getMajor());
        people.setAge(peopleDTO.getAge());
        people.setCode(peopleDTO.getCode());
        people.setAddress(peopleDTO.getAddress());
        people.setStatus(peopleDTO.getStatus());
        int result=peopleMapper.savePeople(people);
        if(result!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "新增人员失败");
        }
    }

    /**
     * 根据ID查询学生信息
     * @param id
     * @return
     */
    @Override
    public People getPeople(Integer id){
        People people=peopleMapper.getPeople(id);
    if(people==null){
        throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该学生");
    }
    return people;
    }

    /**
     * 删除学生
     * @param id
     */
    @Override
    public void deletePeople(Integer id){
        People people=peopleMapper.getPeople(id);
        if(people==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"不存在该学生");
        }
        peopleMapper.delete(id);
    }

    /**
     * 编辑学生
     * @param id
     * @param peopleDTO
     */
    @Override
    public void editPeople(Integer id,PeopleDTO peopleDTO){
        People people = peopleMapper.getPeople(id);
        if(people==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有该学生");
        }
        people.setName(peopleDTO.getName());
        people.setSex(peopleDTO.getSex());
        people.setAge(peopleDTO.getAge());
        people.setMajor(peopleDTO.getMajor());
        people.setCode(peopleDTO.getCode());
        people.setAddress(peopleDTO.getAddress());
        people.setStatus(peopleDTO.getStatus());

        int result = peopleMapper.updatePeople(people);
        if (result <= 0) {
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "学生更新失败");
        }
    }

    /**
     * 上传头像
     */
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Override
    public void uploadAvatar(Integer id, MultipartFile file) {
        People people = peopleMapper.getPeople(id);
        if (people == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "不存在该学生");
        }

        // 方法的具体实现需要依赖具体的文件上传业务逻辑, 这里仅提供一个示例。
        String avatarUrl = uploadFileToLocalServer(file);


        people.setAvatar(avatarUrl);
            int result = peopleMapper.updateAvatar(people);
            if (result <= 0) {
                throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "学生头像更新失败");
        }
    }

    private String uploadFileToLocalServer(MultipartFile file) {
        try {
            // Step 1: 生成目标文件名
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String targetFilename = UUID.randomUUID().toString().replace("-", "") + extension;

            // Step 2: 创建目标文件的目录结构
            File targetDirectory = new File(uploadDir + "/avatars/");
            if (!targetDirectory.exists()) {
                targetDirectory.mkdirs();
            }

            // Step 3: 将文件写入目标目录
            File targetFile = new File(targetDirectory, targetFilename);
            file.transferTo(targetFile);

            // Step 4: 返回相对路径
            return "/avatars/" + targetFilename;
        } catch (IOException e) {
            log.error("文件上传发生错误", e);
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "文件上传失败");
        }
    }

    /**
     * 获取头像
     * @return
     */
    @Override
         public List<AvatarVO> getAvatarList(){
        List<AvatarVO> avatarVOList=peopleMapper.getAvatarList();
        return avatarVOList;
         }
}


